import React, { useEffect, useMemo } from 'react';
import { Form, Select, Input } from 'antd';
import { withRouter } from 'umi';

import {
    housePlaceEnum,
    socialTypeEnum,
    socialTypeStatus,
    insuranceBaseTypeEnum,
    decimalTypeEnum,
    baseTypeStatus
} from '@/pages/SalaryManage/enum';
import { NumberSettingInput, PercentSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import LimitInput from '@/components/LimitInput';
import CityCascader, { getAreaItemPath } from '@/pages/SalaryManage/components/CityCascader';
import { OrganizationNameConnect } from '@/pages/SalaryManage/components/OrganizationName';

const { Option } = Select;

/**
 * 编辑模态框
 * @param form Form.create()的实例
 * @param model 实始化数据
 * @param location 地址
 * @param organizationCode
 * @constructor
 */
const MedicalSocialSecurityForm = ({ form, model, location, organizationCode }) => {
    const { getFieldDecorator, getFieldValue } = form;

    const numberOption = (name, required = true) => ({
        validateFirst: true,
        rules: [
            ...(required
                ? [
                      {
                          required: true,
                          message: `请填写【${name}】`
                      }
                  ]
                : []),
            {
                validator(rule, value, callback) {
                    if (value && +value < 0) {
                        callback(new Error());
                    } else {
                        callback();
                    }
                },
                message: `【${name}】不能小于0`
            },
            {
                validator(rule, value, callback) {
                    if (value && +value > 1000000000) {
                        callback(new Error());
                    } else {
                        callback();
                    }
                },
                message: `【${name}】不能超过10亿`
            },
            {
                validator(rule, value, callback) {
                    if (value && value.length > 12) {
                        callback(new Error());
                    } else {
                        callback();
                    }
                },
                message: `【${name}】输入长度不能大于12`
            }
        ]
    });
    const percentOption = (name, required = true) => ({
        validateFirst: true,
        rules: [
            ...(required
                ? [
                      {
                          required: true,
                          message: `请填写【${name}】`
                      }
                  ]
                : []),
            {
                type: 'number',
                min: 0,
                message: `【${name}】不能小于0`
            },
            {
                type: 'number',
                max: 1,
                message: `【${name}】不能超过100%`
            },
            {
                type: 'number',
                message: `【${name}】输入长度不能大于12`
            }
        ]
    });

    const isNew = !model?.id;
    const wrapperCol = isNew ? { span: 11 } : { span: 17 };
    const remarkWrapperCol = { span: 17 };
    const { socialCityCode } = location.query;
    const initAreaItemArray = useMemo(() => (socialCityCode == null ? null : getAreaItemPath(socialCityCode)), [
        socialCityCode
    ]);
    const initAreaItemValueArray = useMemo(
        () => (initAreaItemArray != null ? initAreaItemArray.map(item => item.code) : null),
        [initAreaItemArray]
    );
    useEffect(() => {
        form.setFieldsValue({ v_areaItemArray: initAreaItemArray });
    }, [initAreaItemArray]);

    const onChange = (valueArray, areaItemArray) => {
        form.setFieldsValue({ v_areaItemArray: areaItemArray });
    };

    const handleMinPayAmt = minPayAmt => {
        form.setFieldsValue({
            limitDownAmt: minPayAmt
        });
    };
    const handleBasePayAmt = basePayAmt => {
        form.setFieldsValue({
            basePayAmt
        });
    };
    const handleSocialTypeChange = socialType => {
        // （4.1）险金种类=公积金时：【基数取值=基本月薪+月绩效奖】，不分户籍本外地；
        // （4.2）险金种类=其他五险时，户籍本地【基数取值=基本月薪+月绩效奖】，户籍外地【基数取值=基本月薪】
        // （4.3）险金种类=大病医疗时，抱持目前逻辑，以上新增字段置灰。

        if (socialType === socialTypeStatus.SERIOUS_ILL) {
            form.setFieldsValue({
                minPayAmt: null,
                companyRate: null,
                personRate: null,
                limitDownAmt: null,
                baseType: null,
                roundingType: null
            });
        } else if (socialType === socialTypeStatus.FUND) {
            form.setFieldsValue({
                baseType: baseTypeStatus.BASEANDBONUS
            });
        } else if (getFieldValue('housePlace') === 1) {
            form.setFieldsValue({
                baseType: baseTypeStatus.BASEANDBONUS
            });
        } else {
            form.setFieldsValue({
                baseType: baseTypeStatus.BASE
            });
        }
    };
    const insuranceBaseTypeEnumChange = baseType => {
        form.setFieldsValue({
            baseType
        });
        if (baseType === baseTypeStatus.FIX) {
            form.setFieldsValue({
                limitDownAmt: null,
                limitUpperAmt: null
            });
        }
    };
    const handleHousePlaceChange = housePlace => {
        const { OLD, UN_EMPLOY, HOSPITAL, BIRTH, HARM } = socialTypeStatus;
        if ([OLD, UN_EMPLOY, HOSPITAL, BIRTH, HARM].includes(getFieldValue('socialType'))) {
            if (housePlace === 1) {
                form.setFieldsValue({
                    baseType: baseTypeStatus.BASEANDBONUS
                });
            } else {
                form.setFieldsValue({
                    baseType: baseTypeStatus.BASE
                });
            }
        }
    };
    return (
        <Form layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ ...wrapperCol }}>
            {isNew ? (
                <>
                    {getFieldDecorator('v_areaItemArray')(<Input type="hidden" />)}
                    {getFieldDecorator('organizationCode', {
                        initialValue: model?.organizationCode || organizationCode
                    })(<Input type="hidden" />)}

                    <Form.Item label="行政机构：">
                        <OrganizationNameConnect organizationCode={organizationCode} />
                    </Form.Item>

                    <Form.Item label="所属城市：">
                        {getFieldDecorator('v_city', {
                            initialValue: initAreaItemValueArray,
                            first: true,
                            rules: [
                                { required: true, message: '请选择【所属城市】' },
                                {
                                    validator: (rule, value) => !value || value.length !== 1,
                                    message: '请选择市区'
                                }
                            ]
                        })(<CityCascader cityParentId={39} showSearch onChange={onChange} />)}
                    </Form.Item>

                    <Form.Item label="户籍归属">
                        {getFieldDecorator('housePlace', {
                            initialValue: model?.housePlace,
                            rules: [{ required: true, message: '请选择【户籍归属】' }]
                        })(
                            <Select placeholder="请选择" onChange={handleHousePlaceChange}>
                                {housePlaceEnum.list().map(enumItem => (
                                    <Option key={enumItem.value} value={enumItem.value}>
                                        {enumItem.text}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                </>
            ) : null}

            <Form.Item label="险金种类：">
                {getFieldDecorator('socialType', {
                    initialValue: model?.socialType,
                    rules: [{ required: true, message: '请选择【险金种类】' }]
                })(
                    <Select placeholder="请选择" disabled={!isNew} onChange={handleSocialTypeChange}>
                        {socialTypeEnum.list('index').map(enumItem => (
                            <Option key={enumItem.value} value={enumItem.value}>
                                {enumItem.text}
                            </Option>
                        ))}
                    </Select>
                )}
            </Form.Item>

            <Form.Item label="基数取值：">
                {getFieldDecorator('baseType', {
                    initialValue: model?.baseType,
                    rules: [
                        {
                            required: getFieldValue('socialType') !== socialTypeStatus.SERIOUS_ILL,
                            message: '请选择【基数取值】'
                        }
                    ]
                })(
                    <Select
                        placeholder="请选择"
                        disabled={getFieldValue('socialType') === socialTypeStatus.SERIOUS_ILL}
                        onChange={insuranceBaseTypeEnumChange}
                    >
                        {insuranceBaseTypeEnum.list('index').map(enumItem => (
                            <Option key={enumItem.value} value={enumItem.value}>
                                {enumItem.text}
                            </Option>
                        ))}
                    </Select>
                )}
            </Form.Item>

            {getFieldValue('baseType') === baseTypeStatus.FIX ? (
                <Form.Item label="缴交基数：">
                    {getFieldDecorator('basePayAmt', {
                        initialValue: model?.basePayAmt ?? null,
                        ...numberOption('缴交基数', getFieldValue('socialType') !== socialTypeStatus.SERIOUS_ILL)
                    })(
                        <NumberSettingInput
                            thousandsSeparator=","
                            maxLength={15}
                            nonNegative
                            placeholder="请输入"
                            onChange={handleBasePayAmt}
                        />
                    )}
                </Form.Item>
            ) : (
                <Form.Item label="最低缴交基数：">
                    {getFieldDecorator('minPayAmt', {
                        initialValue: model?.minPayAmt ?? null,
                        ...numberOption('最低缴交基数', getFieldValue('socialType') !== socialTypeStatus.SERIOUS_ILL)
                    })(
                        <NumberSettingInput
                            thousandsSeparator=","
                            maxLength={15}
                            nonNegative
                            placeholder="请输入"
                            onChange={handleMinPayAmt}
                            disabled={getFieldValue('socialType') === socialTypeStatus.SERIOUS_ILL}
                        />
                    )}
                </Form.Item>
            )}

            <Form.Item label="单位比例：">
                {getFieldDecorator('companyRate', {
                    initialValue: model?.companyRate ?? null,
                    ...percentOption('单位比例', getFieldValue('socialType') !== socialTypeStatus.SERIOUS_ILL)
                })(
                    <PercentSettingInput
                        thousandsSeparator=","
                        maxLength={15}
                        nonNegative
                        placeholder="请输入"
                        disabled={getFieldValue('socialType') === socialTypeStatus.SERIOUS_ILL}
                    />
                )}
            </Form.Item>

            <Form.Item label="个人比例：">
                {getFieldDecorator('personRate', {
                    initialValue: model?.personRate ?? null,
                    ...percentOption('个人比例', getFieldValue('socialType') !== socialTypeStatus.SERIOUS_ILL)
                })(
                    <PercentSettingInput
                        thousandsSeparator=","
                        maxLength={15}
                        nonNegative
                        placeholder="请输入"
                        disabled={getFieldValue('socialType') === socialTypeStatus.SERIOUS_ILL}
                    />
                )}
            </Form.Item>

            <Form.Item label="上限：">
                {getFieldDecorator('limitUpperAmt', {
                    initialValue: model?.limitUpperAmt ?? null,
                    ...numberOption(
                        '上限',
                        getFieldValue('socialType') === socialTypeStatus.SERIOUS_ILL ||
                            getFieldValue('baseType') !== baseTypeStatus.FIX
                    )
                })(
                    <NumberSettingInput
                        thousandsSeparator=","
                        maxLength={15}
                        nonNegative
                        placeholder="请输入"
                        disabled={getFieldValue('baseType') === baseTypeStatus.FIX}
                    />
                )}
            </Form.Item>

            <Form.Item label="下限：">
                {getFieldDecorator('limitDownAmt', {
                    initialValue: model?.limitDownAmt ?? null,
                    rules: [
                        {
                            required: false,
                            message: '请输入【最低缴交基数】'
                        }
                    ]
                })(
                    <NumberSettingInput
                        placeholder="请输入"
                        thousandsSeparator=","
                        maxLength={15}
                        nonNegative
                        disabled
                    />
                )}
            </Form.Item>

            <Form.Item label="小数位：">
                {getFieldDecorator('roundingType', {
                    initialValue: model?.roundingType,
                    rules: [
                        {
                            required: getFieldValue('socialType') !== socialTypeStatus.SERIOUS_ILL,
                            message: '请选择【小数位】'
                        }
                    ]
                })(
                    <Select
                        placeholder="请选择"
                        disabled={getFieldValue('socialType') === socialTypeStatus.SERIOUS_ILL}
                    >
                        {decimalTypeEnum.list('index').map(enumItem => (
                            <Option key={enumItem.value} value={enumItem.value}>
                                {enumItem.text}
                            </Option>
                        ))}
                    </Select>
                )}
            </Form.Item>

            <Form.Item label="备注说明：" wrapperCol={{ ...remarkWrapperCol }}>
                {getFieldDecorator('remark', {
                    initialValue: model?.remark
                })(<LimitInput maxLength={500} area showNumber rows={3} placeholder="请输入备注信息..." />)}
            </Form.Item>
        </Form>
    );
};

export default withRouter(MedicalSocialSecurityForm);
